import Parser from 'rss-parser';
import fs from 'fs';
import path from 'path';

// 配置自定义字段映射以支持 media:content
const parser = new Parser({
  customFields: {
    item: [
      ['media:content', 'mediaContent', { keepArray: true }],
      ['media:thumbnail', 'mediaThumbnail'],
      ['dc:creator', 'creator']
    ]
  }
});
const rssUrl = 'https://aibusiness.com/rss.xml';

async function testRSS() {
  try {
    console.log('正在获取 RSS 订阅...');
    const feed = await parser.parseURL(rssUrl);
    
    console.log('\n=== RSS 订阅信息 ===');
    console.log('标题:', feed.title);
    console.log('描述:', feed.description);
    console.log('链接:', feed.link);
    console.log('最后更新时间:', feed.lastBuildDate || feed.pubDate);
    console.log(`\n总共获取到 ${feed.items.length} 篇文章\n`);
    
    // 显示所有文章
    console.log('=== 所有文章列表 ===\n');
    feed.items.forEach((item, index) => {
      console.log(`${index + 1}. ${item.title}`);
      console.log(`   链接: ${item.link}`);
      console.log(`   发布时间: ${item.pubDate || '未知'}`);
      if (item.creator) {
        console.log(`   作者: ${item.creator}`);
      }
      if (item.contentSnippet || item.content) {
        const snippet = item.contentSnippet || item.content || '';
        console.log(`   摘要: ${snippet.substring(0, 150)}${snippet.length > 150 ? '...' : ''}`);
      }
      // 显示图片
      const imageUrl = item.mediaContent?.[0]?.$?.url || item.mediaThumbnail?.$?.url || item.enclosure?.url || '';
      if (imageUrl) {
        console.log(`   图片: ${imageUrl}`);
      }
      console.log('');
    });
    
    // 保存完整数据到 JSON 文件
    const outputPath = path.join(process.cwd(), 'aibusiness-rss-data.json');
    const outputData = {
      feed: {
        title: feed.title,
        description: feed.description,
        link: feed.link,
        lastBuildDate: feed.lastBuildDate || feed.pubDate,
        itemCount: feed.items.length
      },
      items: feed.items.map(item => ({
        title: item.title,
        link: item.link,
        pubDate: item.pubDate,
        creator: item.creator,
        description: item.contentSnippet || item.content || item.description,
        guid: item.guid,
        imageUrl: item.mediaContent?.[0]?.$?.url || item.mediaThumbnail?.$?.url || item.enclosure?.url || null
      }))
    };
    
    fs.writeFileSync(outputPath, JSON.stringify(outputData, null, 2), 'utf-8');
    console.log(`\n✅ 完整数据已保存到: ${outputPath}`);
    
  } catch (error) {
    console.error('获取 RSS 失败:', error.message);
    if (error.code === 'ENOTFOUND') {
      console.error('网络连接失败，请检查网络');
    } else if (error.code === 'ECONNREFUSED') {
      console.error('连接被拒绝，请检查 URL 是否正确');
    }
  }
}

testRSS();

